<template>
  <div style="display: flex;width: 100%;justify-content: center;">
    <!-- 下拉选择考试 -->
    <el-select v-model="currentUserInfo.id" placeholder="请选择" @change="showUpdateNoticeDialog">
      <el-option
        v-for="item in allexamInfo"
        :key="item.examId"
        :label="item.examName"
        :value="item.examId">
      </el-option>
    </el-select>

    <!-- 折线图容器 -->
    <div id="lineChart" style="width: 1200px; height: 400px;"></div>
  </div>
</template>

<script>
import exam from '@/api/exam'
export default {
  name: 'AllKaoshi',
  data() {
    return {
      allexamInfo: [],
      chartData: {
        categories: [],
        values: []
      },
      currentUserInfo: {}
    }
  },
  created() {
    this.getAllExamInfo();
  },
  methods: {

    // 获取考试列表
    getAllExamInfo() {
      exam.allExamInfo().then((resp) => {
        if (resp.code === 200) {
          this.allexamInfo = resp.data;
        }
      })
    },

    // **折线图绘制方法**
    drawLineChart() {
      this.$nextTick(() => {
        let chartDom = document.getElementById('lineChart');
        if (!chartDom) {
          console.error("折线图容器不存在");
          return;
        }

        let myChart = this.$echarts.init(chartDom);

        if (!this.chartData.categories.length || !this.chartData.values.length) {
          console.warn("折线图数据为空");
          return;
        }

        // **动态计算最高分作为 y 轴最大值**
        let maxScore = Math.max(...this.chartData.values) || 100; // 避免 0 值情况，默认 100

        myChart.setOption({
          title: {
            text: '考试成绩折线图',
            x: 'center',
          },
          tooltip: {
            trigger: 'axis',
            formatter: (params) => {
              let tooltipContent = `<strong>${params[0].seriesName}</strong><br/>`;
              params.forEach((param) => {
                tooltipContent += `${param.name}: ${param.value} 分<br/>`;
              });
              return tooltipContent;
            }
          },
          xAxis: {
            type: 'category',
            data: this.chartData.categories,
            axisLabel: {color: '#409EFF'}
          },
          yAxis: {
            type: 'value',
            max: maxScore + 10, // 让 Y 轴略高于最高分
            axisLabel: {formatter: '{value} 分', color: '#409EFF'}
          },
          series: [{
            name: '考试成绩',
            type: 'line',
            data: this.chartData.values, // **直接使用原始分数**
            lineStyle: {color: '#409EFF'},
            itemStyle: {color: '#409EFF'},
            areaStyle: {color: 'rgba(64,158,255,0.3)'}
          }]
        });
      });
    },

    // **考试选择后更新折线图**
    showUpdateNoticeDialog(examId) {
      console.log("选中的考试ID:", examId);

      exam.getAllExamData(examId).then((resp) => {
        console.log("返回的考试数据:", resp.data);

        if (!resp.data || !resp.data.length) {
          console.warn("考试数据为空");
          return;
        }

        // **更新折线图数据**
        // categories: resp.data.map(item => item.userAnswers),
        this.chartData = {
          categories: resp.data.map(item => ""),
          values: resp.data.map(item => item.totalScore)
        };

        // **调用折线图绘制**
        this.drawLineChart();
      });
    },
  }
}
</script>
